'use server'

import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'
import { Decimal } from '@prisma/client/runtime/library'

interface IncomeData {
  amount: string
  description: string
}

export async function createIncome(data: IncomeData) {
  try {
    const income = await prisma.financeRecord.create({
      data: {
        type: 'INCOME',
        amount: new Decimal(data.amount),
        description: data.description
      }
    })

    const serializedIncome = {
      ...income,
      amount: income.amount.toString(),
      createdAt: income.createdAt.toISOString(),
      updatedAt: income.updatedAt.toISOString()
    }

    revalidatePath('/dashboard/finance/income')
    return { success: true, data: serializedIncome }
  } catch (error) {
    console.error('创建收入记录失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '创建收入记录失败'
    }
  }
}

export async function updateIncome(id: number, data: IncomeData) {
  try {
    const income = await prisma.financeRecord.update({
      where: { id },
      data: {
        amount: new Decimal(data.amount),
        description: data.description
      }
    })

    const serializedIncome = {
      ...income,
      amount: income.amount.toString(),
      createdAt: income.createdAt.toISOString(),
      updatedAt: income.updatedAt.toISOString()
    }

    revalidatePath('/dashboard/finance/income')
    return { success: true, data: serializedIncome }
  } catch (error) {
    console.error('更新收入记录失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '更新收入记录失败'
    }
  }
}

export async function deleteIncome(id: number) {
  try {
    await prisma.financeRecord.delete({
      where: { id }
    })

    revalidatePath('/dashboard/finance/income')
    return { success: true }
  } catch (error) {
    console.error('删除收入记录失败:', error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '删除收入记录失败'
    }
  }
} 